<template>
  <div class="service-container">
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <h3>通知草稿箱</h3>
          <div class="header-right">
            <el-button type="primary" @click="handleCreate" class="add-btn">
              <el-icon><Plus /></el-icon>新建通知
            </el-button>
            <div class="search-toggle-area">
              <el-button class="search-toggle-button" @click="toggleSearchBar">
                <el-icon><Search /></el-icon>
              </el-button>
              <el-form :inline="true" :model="searchParams" class="search-form" :class="{'is-hidden': !showSearchBar}">
                <div class="search-form-row">
                  <el-form-item label="类型">
                    <el-select v-model="selectedType" placeholder="全部类型" clearable @change="handleSearch" style="width: 150px;">
                      <el-option label="园区公告" value="园区公告"></el-option>
                      <el-option label="新闻资讯" value="新闻资讯"></el-option>
                      <el-option label="审批提醒" value="审批提醒"></el-option>
                      <el-option label="业务提醒" value="业务提醒"></el-option>
                      <el-option label="合同提醒" value="合同提醒"></el-option>
                      <el-option label="缴费提醒" value="缴费提醒"></el-option>
                      <el-option label="活动推广" value="活动推广"></el-option>
                      <el-option label="系统通知" value="系统通知"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="标题">
                    <el-input
                      v-model="searchQuery"
                      placeholder="请输入通知标题"
                      style="width: 220px;"
                      clearable
                      @clear="handleSearch"
                      @keyup.enter="handleSearch"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </template>

      <!-- 卡片式布局替代表格 -->
      <div v-loading="loading" class="draft-cards">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="item in tableData" :key="item.id" class="card-col">
            <el-card shadow="hover" class="draft-card">
              <div class="card-header">
                <span class="card-type" :class="getTypeClass(item.message_type)">{{ item.message_type }}</span>
                <el-dropdown trigger="click">
                  <span class="el-dropdown-link">
                    <el-icon><MoreFilled /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="showEditForm(item.id)">
                        <el-icon><EditPen /></el-icon> 编辑草稿
                      </el-dropdown-item>
                      <el-dropdown-item @click="handlePublish(item.id)">
                        <el-icon><Promotion /></el-icon> 发布通知
                      </el-dropdown-item>
                      <el-dropdown-item @click="showDeleteConfirm(item.id)" divided>
                        <el-icon><Delete /></el-icon> 删除草稿
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="card-body" @click="showEditForm(item.id)">
                <h3 class="card-title">{{ item.title }}</h3>
                <div class="card-preview" v-html="getContentPreview(item.content)"></div>
              </div>
              <div class="card-footer">
                <div class="time-info">
                  <div class="time-item">
                    <el-icon><Calendar /></el-icon>
                    <span>创建: {{ formatDate(item.created_at) }}</span>
                  </div>
                  <div class="time-item">
                    <el-icon><Timer /></el-icon>
                    <span>更新: {{ formatDate(item.updated_at) }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 没有数据时显示 -->
        <div v-if="tableData.length === 0 && !loading" class="no-data">
          <el-empty description="暂无草稿通知" :image-size="120">
            <el-button type="primary" @click="handleCreate">新建通知</el-button>
          </el-empty>
        </div>
      </div>

      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :total="pagination.total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next, jumper"
          background
        ></el-pagination>
      </div>

      <!-- 编辑表单对话框 -->
      <el-dialog
        v-model="editDialogVisible"
        title="编辑草稿通知"
        width="70%"
      >
        <div v-if="editForm" class="edit-form-wrapper">
          <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px" class="notification-form">
            <el-form-item label="标题" prop="title">
              <el-input v-model="editForm.title" placeholder="请输入通知标题"></el-input>
            </el-form-item>
            
            <el-form-item label="消息类型" prop="message_type">
              <el-select v-model="editForm.message_type" placeholder="请选择消息类型" style="width: 100%">
                <el-option label="园区公告" value="园区公告"></el-option>
                <el-option label="新闻资讯" value="新闻资讯"></el-option>
                <el-option label="审批提醒" value="审批提醒"></el-option>
                <el-option label="业务提醒" value="业务提醒"></el-option>
                <el-option label="合同提醒" value="合同提醒"></el-option>
                <el-option label="缴费提醒" value="缴费提醒"></el-option>
                <el-option label="活动推广" value="活动推广"></el-option>
                <el-option label="系统通知" value="系统通知"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="有效期">
              <div style="display: flex; align-items: center; gap: 10px;">
                <el-form-item prop="valid_from" style="margin-bottom: 0; width: 50%;">
                  <el-date-picker
                    v-model="editForm.valid_from"
                    type="datetime"
                    placeholder="开始日期"
                    clearable
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
                <span>至</span>
                <el-form-item prop="valid_until" style="margin-bottom: 0; width: 50%;">
                  <el-date-picker
                    v-model="editForm.valid_until"
                    type="datetime"
                    placeholder="结束日期"
                    clearable
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </div>
            </el-form-item>
            
            <el-form-item label="内容" prop="content">
              <el-input
                type="textarea"
                v-model="editForm.content"
                :rows="8"
                placeholder="请输入通知内容">
              </el-input>
            </el-form-item>

            <el-form-item label="目标受众" prop="target_groups" v-if="showTargetAudience">
              <div class="compact-audience-selection">
                <div class="target-groups">
                  <el-checkbox-group v-model="targetGroups">
                    <el-checkbox label="企业员工"></el-checkbox>
                    <el-checkbox label="物业员工"></el-checkbox>
                  </el-checkbox-group>
                </div>
                <div class="specific-users">
                  <el-select 
                    v-model="specificUsers" 
                    multiple 
                    filterable 
                    remote 
                    reserve-keyword
                    :remote-method="handleSearchUsers" 
                    :loading="searchLoading"
                    placeholder="搜索特定用户..." 
                    style="width: 100%">
                    <el-option
                      v-for="item in userOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                      <div class="user-option">
                        <span>{{ item.label }}</span>
                        <small>{{ item.type }}</small>
                      </div>
                    </el-option>
                  </el-select>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="创建信息" class="info-item">
              <div class="info-content">
                <div class="info-row">
                  <span class="info-label">创建时间:</span>
                  <span class="info-value">{{ formatDate(editForm.created_at) }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">最后更新:</span>
                  <span class="info-value">{{ formatDate(editForm.updated_at) }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">创建者:</span>
                  <span class="info-value">{{ editForm.sender_name }}</span>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveEdit">保存草稿</el-button>
            <el-button type="success" @click="publishFromEdit">发布通知</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="删除确认"
        width="30%"
      >
        <div>确定要删除这个草稿通知吗？此操作不可恢复。</div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="confirmDelete">确定删除</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 新建草稿对话框 -->
      <el-dialog
        v-model="createDialogVisible"
        title="新建通知"
        width="70%"
      >
        <div v-if="createForm" class="create-form-wrapper">
          <el-form :model="createForm" :rules="rules" ref="createFormRef" label-width="100px" class="notification-form">
            <el-form-item label="标题" prop="title">
              <el-input v-model="createForm.title" placeholder="请输入通知标题"></el-input>
            </el-form-item>
            
            <el-form-item label="消息类型" prop="message_type">
              <el-select v-model="createForm.message_type" placeholder="请选择消息类型" style="width: 100%">
                <el-option label="园区公告" value="园区公告"></el-option>
                <el-option label="新闻资讯" value="新闻资讯"></el-option>
                <el-option label="审批提醒" value="审批提醒"></el-option>
                <el-option label="业务提醒" value="业务提醒"></el-option>
                <el-option label="合同提醒" value="合同提醒"></el-option>
                <el-option label="缴费提醒" value="缴费提醒"></el-option>
                <el-option label="活动推广" value="活动推广"></el-option>
                <el-option label="系统通知" value="系统通知"></el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="有效期">
              <div style="display: flex; align-items: center; gap: 10px;">
                <el-form-item prop="valid_from" style="margin-bottom: 0; width: 50%;">
                  <el-date-picker
                    v-model="createForm.valid_from"
                    type="datetime"
                    placeholder="开始日期"
                    clearable
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
                <span>至</span>
                <el-form-item prop="valid_until" style="margin-bottom: 0; width: 50%;">
                  <el-date-picker
                    v-model="createForm.valid_until"
                    type="datetime"
                    placeholder="结束日期"
                    clearable
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </div>
            </el-form-item>
            
            <el-form-item label="内容" prop="content">
              <el-input
                type="textarea"
                v-model="createForm.content"
                :rows="8"
                placeholder="请输入通知内容">
              </el-input>
            </el-form-item>

            <el-form-item label="目标受众" prop="target_groups" v-if="showTargetAudience">
              <div class="compact-audience-selection">
                <div class="target-groups">
                  <el-checkbox-group v-model="targetGroups">
                    <el-checkbox label="企业员工"></el-checkbox>
                    <el-checkbox label="物业员工"></el-checkbox>
                  </el-checkbox-group>
                </div>
                <div class="specific-users">
                  <el-select 
                    v-model="specificUsers" 
                    multiple 
                    filterable 
                    remote 
                    reserve-keyword
                    :remote-method="handleSearchUsers" 
                    :loading="searchLoading"
                    placeholder="搜索特定用户..." 
                    style="width: 100%">
                    <el-option
                      v-for="item in userOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                      <div class="user-option">
                        <span>{{ item.label }}</span>
                        <small>{{ item.type }}</small>
                      </div>
                    </el-option>
                  </el-select>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="createDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveCreate">保存草稿</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { getNotificationList, deleteNotification, getNotificationDetail, updateNotification, publishNotification, createNotification } from '@/api/notifications';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { Search, MoreFilled, EditPen, Promotion, Delete, Calendar, Timer, Plus } from '@element-plus/icons-vue';
import { searchUsers } from '@/api/users';

const router = useRouter();
const selectedType = ref('');
const searchQuery = ref('');
const tableData = ref([]);
const loading = ref(true);
const editDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const deleteItemId = ref(null);
const editForm = ref(null);
const editFormRef = ref(null);
const pagination = ref({
  page: 1,
  size: 12,
  total: 0,
});

// 新增搜索相关变量
const showSearchBar = ref(false);
const searchParams = ref({
  type: '',
  title: ''
});

// 新建草稿对话框
const createDialogVisible = ref(false);
const createForm = ref({
  title: '',
  content: '',
  message_type: '园区公告',
  valid_from: new Date(),
  valid_until: null
});
const createFormRef = ref(null);

const targetGroups = ref(['企业员工']); // 默认选择企业员工
const specificUsers = ref([]); // 特定用户
const userOptions = ref([]); // 用户选项
const searchLoading = ref(false); // 搜索加载状态
const searchKeyword = ref(''); // 搜索关键词
const searchTimeout = ref(null); // 搜索延迟定时器
const showTargetAudience = ref(false); // 是否显示目标受众选项

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  message_type: [
    { required: true, message: '请选择消息类型', trigger: 'change' }
  ],
  valid_from: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '长度在 10 到 5000 个字符', trigger: 'blur' }
  ]
};

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      message_type: selectedType.value,
      title: searchQuery.value,
      publish_time: 'null', // 只获取publish_time为null的消息，即草稿状态
    };
    const res = await getNotificationList(params);
    if (res.data && res.data.code === 200) {
        console.log('API返回的通知列表数据:', res.data.data.list);
        tableData.value = res.data.data.list;
        pagination.value.total = res.data.data.total;
    } else {
        ElMessage.error(res.data.message || '获取通知草稿列表失败');
    }
  } catch (error) {
    console.error('Failed to fetch notification drafts:', error);
    ElMessage.error('获取通知草稿列表失败');
  } finally {
    loading.value = false;
  }
};

// 日期格式化函数
const formatDate = (dateStr) => {
  if (!dateStr) return '暂无';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (e) {
    return dateStr || '暂无';
  }
};

// 获取内容预览
const getContentPreview = (content) => {
  if (!content) return '';
  // 移除HTML标签，只保留纯文本
  const plainText = content.replace(/<[^>]+>/g, '');
  // 返回前50个字符
  return plainText.length > 50 ? plainText.substring(0, 50) + '...' : plainText;
};

onMounted(() => {
  fetchData();
  
  // 测试日期格式化
  console.log('==== 日期格式化测试 ====');
  try {
    const testDate = new Date();
    console.log('当前日期对象:', testDate);
    console.log('ISO字符串:', testDate.toISOString());
    console.log('yyyy-MM-dd HH:mm:ss格式:', testDate.toISOString().slice(0, 19).replace('T', ' '));
    
    // 测试格式转换
    const formattedDate = testDate.toISOString().slice(0, 19).replace('T', ' ');
    console.log('尝试解析格式化后的日期:', new Date(formattedDate));
    
    // 测试el-date-picker使用的格式
    const dateFormatForPicker = testDate.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }) + ' ' + testDate.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    });
    console.log('DatePicker本地格式:', dateFormatForPicker);
    console.log('尝试解析本地格式日期:', new Date(dateFormatForPicker));
  } catch (e) {
    console.error('日期格式化测试失败:', e);
  }
  console.log('========================');
});

// 监听日期选择器的变化
watch(() => editForm.value?.valid_from, (newVal, oldVal) => {
  if (newVal && editForm.value) {
    console.log('编辑表单开始日期变更:', newVal);
    // 确保日期格式正确
    try {
      const date = new Date(newVal);
      if (!isNaN(date.getTime())) {
        // 有效日期，无需处理
        console.log('有效的开始日期');
      } else {
        console.warn('无效的开始日期:', newVal);
      }
    } catch (e) {
      console.error('解析开始日期出错:', e);
    }
  }
});

watch(() => editForm.value?.valid_until, (newVal, oldVal) => {
  if (newVal && editForm.value) {
    console.log('编辑表单结束日期变更:', newVal);
    // 确保日期格式正确
    try {
      const date = new Date(newVal);
      if (!isNaN(date.getTime())) {
        // 有效日期，无需处理
        console.log('有效的结束日期');
      } else {
        console.warn('无效的结束日期:', newVal);
      }
    } catch (e) {
      console.error('解析结束日期出错:', e);
    }
  }
});

watch(() => createForm.value.valid_from, (newVal) => {
  if (newVal) {
    console.log('新建表单开始日期变更:', newVal);
  }
});

watch(() => createForm.value.valid_until, (newVal) => {
  if (newVal) {
    console.log('新建表单结束日期变更:', newVal);
  }
});

const handleSearch = () => {
  pagination.value.page = 1;
  fetchData();
}

const handleCreate = () => {
  // 设置默认结束日期为7天后
  const futureDate = new Date();
  futureDate.setDate(futureDate.getDate() + 7);
  
  createForm.value = {
    title: '',
    content: '',
    message_type: '园区公告',
    valid_from: new Date(),
    valid_until: futureDate
  };
  createDialogVisible.value = true;
  // 重置特定用户
  specificUsers.value = [];
  // 预设目标受众
  presetTargetGroups('园区公告');
  // 显示目标受众选项
  showTargetAudience.value = true;
};

const handlePageChange = (page) => {
  pagination.value.page = page;
  fetchData();
};

// 不同消息类型推荐的目标受众
const audienceRecommendations = {
  '园区公告': ['企业员工', '物业员工'],
  '新闻资讯': ['企业员工'],
  '审批提醒': ['企业员工'],
  '业务提醒': ['企业员工', '物业员工'],
  '合同提醒': ['企业员工'],
  '缴费提醒': ['企业员工'],
  '活动推广': ['企业员工'],
  '系统通知': ['企业员工', '物业员工']
};

// 获取消息类型对应的受众建议
const getAudienceRecommendation = (messageType) => {
  if (messageType && audienceRecommendations[messageType]) {
    const groups = audienceRecommendations[messageType].join('、');
    return `建议发送给：${groups}`;
  }
  return '请选择适合的目标受众';
};

// 根据消息类型预设目标受众
const presetTargetGroups = (messageType) => {
  console.log('预设目标受众，消息类型:', messageType);
  
  if (messageType && audienceRecommendations[messageType]) {
    targetGroups.value = [...audienceRecommendations[messageType]];
  } else {
    targetGroups.value = ['企业员工'];
  }
  
  console.log('预设后的目标受众:', targetGroups.value);
  
  // 确保targetGroups是一个有效的数组
  if (!Array.isArray(targetGroups.value)) {
    console.warn('目标受众不是数组，重置为默认值');
    targetGroups.value = ['企业员工'];
  }
};

// 搜索用户
const handleSearchUsers = (query) => {
  searchKeyword.value = query;
  if (query.length < 2) {
    userOptions.value = [];
    return;
  }
  
  // 清除之前的定时器（防抖）
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value);
  }
  
  // 设置定时器延迟300毫秒执行搜索（防抖）
  searchTimeout.value = setTimeout(() => {
    searchLoading.value = true;
    
    searchUsers(query).then(response => {
      if (response.data && response.data.code === 200) {
        userOptions.value = response.data.data.map(item => {
          return {
            value: item.id,
            label: item.name || item.username,
            type: item.type
          };
        });
      } else {
        userOptions.value = [];
      }
    }).catch(() => {
      userOptions.value = [];
    }).finally(() => {
      searchLoading.value = false;
    });
  }, 300);
};

// 验证目标受众是否有效
const validateAudience = () => {
  // 确保数组存在且不为空
  const hasGroups = targetGroups.value && Array.isArray(targetGroups.value) && targetGroups.value.length > 0;
  const hasUsers = specificUsers.value && Array.isArray(specificUsers.value) && specificUsers.value.length > 0;
  
  // 调试输出当前受众信息
  console.log('验证受众 - 目标群体:', targetGroups.value);
  console.log('验证受众 - 特定用户:', specificUsers.value);
  
  return hasGroups || hasUsers;
};

// 直接显示编辑表单
const showEditForm = async (id) => {
  if (!id) return;
  
  const loadingInstance = ElLoading.service({
    target: '.app-container',
    text: '加载草稿内容...',
    background: 'rgba(255, 255, 255, 0.7)'
  });
  
  try {
    const res = await getNotificationDetail(id);
    if (res.data && res.data.code === 200) {
      console.log('API返回的通知详情数据:', res.data.data);
      
      // 准备表单数据
      editForm.value = {
        id: res.data.data.id,
        title: res.data.data.title,
        content: res.data.data.content,
        message_type: res.data.data.message_type,
        valid_from: res.data.data.valid_from ? new Date(res.data.data.valid_from) : null,
        valid_until: res.data.data.valid_until ? new Date(res.data.data.valid_until) : null,
        sender_name: res.data.data.sender_name,
        created_at: res.data.data.created_at,
        updated_at: res.data.data.updated_at
      };
      
      // 根据消息类型预设目标受众
      presetTargetGroups(editForm.value.message_type);
      
      // 重置特定用户
      specificUsers.value = [];
      
      // 尝试获取现有的目标受众设置
      try {
        // 这里可以通过API获取现有的目标受众设置，如果有的话
        // 如果需要从后端获取现有的广播设置，可以在这里添加代码
      } catch (error) {
        console.error('获取目标受众设置失败:', error);
      }
      
      // 显示目标受众选项
      showTargetAudience.value = true;
      
      // 显示编辑对话框
      editDialogVisible.value = true;
    } else {
      ElMessage.error(res.data.message || '获取草稿详情失败');
    }
  } catch (error) {
    console.error('获取草稿详情失败:', error);
    ElMessage.error('获取草稿详情失败');
  } finally {
    loadingInstance.close();
  }
};

// 保存编辑
const saveEdit = async () => {
  if (!editForm.value || !editForm.value.id) return;
  
  // 进行表单校验
  if (!editFormRef.value) return;
  
  editFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
    try {
      // 日期将是Date对象，或在清除后为null
      const validFromDate = editForm.value.valid_from;
      const validUntilDate = editForm.value.valid_until;
      
      // 构建提交的表单数据
      const formData = {
        title: editForm.value.title,
        content: editForm.value.content,
        message_type: editForm.value.message_type,
        valid_from: validFromDate ? validFromDate.toISOString() : null,
        valid_until: validUntilDate ? validUntilDate.toISOString() : null
      };
      
      console.log('提交的表单数据:', formData);
      
      const loadingInstance = ElLoading.service({
        target: '.el-dialog',
        text: '保存中...',
        background: 'rgba(255, 255, 255, 0.7)'
      });
      
      try {
        const response = await updateNotification(editForm.value.id, formData);
        console.log('更新响应:', response);
        
        if (response.data && response.data.code === 200) {
          ElMessage.success('草稿保存成功');
          editDialogVisible.value = false;
          fetchData(); // 刷新列表
        } else {
          ElMessage.error(response.data?.message || '保存失败');
        }
      } finally {
        loadingInstance.close();
      }
    } catch (error) {
      console.error('保存草稿失败:', error);
      if (error.response) {
        console.error('错误响应:', error.response.data);
        ElMessage.error(`保存草稿失败: ${error.response.data?.message || error.response.status}`);
      } else {
        ElMessage.error('保存草稿失败: ' + (error.message || '未知错误'));
      }
    }
  });
};

// 从编辑表单发布通知
const publishFromEdit = async () => {
  if (!editForm.value || !editForm.value.id) return;
  
  // 先进行表单校验
  if (!editFormRef.value) return;
  
  editFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息再发布');
      return;
    }
    
    // 检查是否至少选择了一个目标受众
    if (!validateAudience()) {
      ElMessage.warning('请至少选择一个目标群体或特定用户');
      return;
    }
    
    const loadingInstance = ElLoading.service({
      target: '.el-dialog',
      text: '正在发布通知...',
      background: 'rgba(255, 255, 255, 0.7)'
    });
    
    try {
      const validFromDate = editForm.value.valid_from;
      const validUntilDate = editForm.value.valid_until;
      
      // 先保存最新的表单数据
      const formData = {
        title: editForm.value.title,
        content: editForm.value.content,
        message_type: editForm.value.message_type,
        valid_from: validFromDate ? validFromDate.toISOString() : null,
        valid_until: validUntilDate ? validUntilDate.toISOString() : null
      };
      
      console.log('保存表单数据:', formData);
      
      // 先更新草稿内容
      try {
        await updateNotification(editForm.value.id, formData);
      } catch (error) {
        console.error('更新草稿内容失败:', error);
        loadingInstance.close();
        if (error.response) {
          ElMessage.error(`更新草稿内容失败: ${error.response.data?.message || error.response.status}`);
        } else {
          ElMessage.error('更新草稿内容失败: ' + (error.message || '未知错误'));
        }
        return;
      }
      
      // 定义目标受众
      let publishData = {
        target_groups: targetGroups.value,
        specific_users: specificUsers.value
      };
      
      // 确保数组不为空且格式正确
      if (!publishData.target_groups || !Array.isArray(publishData.target_groups)) {
        publishData.target_groups = [];
      }
      
      if (!publishData.specific_users || !Array.isArray(publishData.specific_users)) {
        publishData.specific_users = [];
      }
      
      // 调试输出
      console.log('发布通知ID:', editForm.value.id);
      console.log('发布数据:', JSON.stringify(publishData));
      
      // 再次验证是否有目标受众
      if (publishData.target_groups.length === 0 && publishData.specific_users.length === 0) {
        loadingInstance.close();
        ElMessage.warning('请至少选择一个目标群体或特定用户');
        return;
      }
      
      // 发布通知
      const response = await publishNotification(editForm.value.id, publishData);
      console.log('发布响应:', response.data);
      
      if (response.data && response.data.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('通知发布成功');
        
        // 弹窗询问用户是否前往已发布通知列表
        ElMessageBox.confirm(
          '通知已成功发布。是否查看已发布的通知列表？',
          '发布成功',
          {
            confirmButtonText: '前往通知列表',
            cancelButtonText: '留在当前页面',
            type: 'success',
            center: true
          }
        )
          .then(() => {
            // 跳转到已发布通知列表
            router.push({ name: 'NotificationManagement' });
          })
          .catch(() => {
            // 留在当前页面，刷新列表
            fetchData();
          });
      } else {
        ElMessage.error(response.data?.message || '发布失败');
      }
    } catch (error) {
      console.error('发布通知失败:', error);
      if (error.response) {
        ElMessage.error(`发布通知失败: ${error.response.data?.message || error.response.status}`);
      } else {
        ElMessage.error('发布通知失败: ' + (error.message || '未知错误'));
      }
    } finally {
      loadingInstance.close();
    }
  });
};

const showDeleteConfirm = (id) => {
  deleteItemId.value = id;
  deleteDialogVisible.value = true;
};

const confirmDelete = async () => {
  if (!deleteItemId.value) return;
  
  try {
    await deleteNotification(deleteItemId.value);
    ElMessage.success('删除草稿成功');
    deleteDialogVisible.value = false;
    fetchData(); // 刷新列表
  } catch (error) {
    ElMessage.error('删除草稿失败');
  }
};

// 处理直接发布
const handlePublish = async (id) => {
  if (!id) return;
  
  const loadingInstance = ElLoading.service({
    target: '.app-container',
    text: '加载通知内容...',
    background: 'rgba(255, 255, 255, 0.7)'
  });
  
  try {
    const res = await getNotificationDetail(id);
    if (res.data && res.data.code === 200) {
      loadingInstance.close();
      
      // 准备表单数据，但不直接显示编辑对话框
      editForm.value = {
        id: res.data.data.id,
        title: res.data.data.title,
        content: res.data.data.content,
        message_type: res.data.data.message_type,
        valid_from: res.data.data.valid_from ? new Date(res.data.data.valid_from) : null,
        valid_until: res.data.data.valid_until ? new Date(res.data.data.valid_until) : null,
        sender_name: res.data.data.sender_name,
        created_at: res.data.data.created_at,
        updated_at: res.data.data.updated_at
      };
      
      // 根据消息类型预设目标受众
      presetTargetGroups(editForm.value.message_type);
      
      // 重置特定用户
      specificUsers.value = [];
      
      // 显示目标受众选项
      showTargetAudience.value = true;
      
      // 弹出确认对话框，让用户确认发布信息
      ElMessageBox.confirm(
        `<div style="text-align:left;">
          <p><strong>标题:</strong> ${editForm.value.title}</p>
          <p><strong>类型:</strong> ${editForm.value.message_type}</p>
          <p><strong>目标受众:</strong> ${targetGroups.value.join('、')}</p>
          <p style="margin-top:10px;"><i>确认要发布此通知吗？您可以选择编辑详情或直接发布</i></p>
        </div>`,
        '发布通知',
        {
          confirmButtonText: '确认发布',
          cancelButtonText: '编辑详情',
          dangerouslyUseHTMLString: true,
          distinguishCancelAndClose: true,
          type: 'info',
          center: true
        }
      ).then(() => {
        // 用户确认发布，再次验证受众
        if (!validateAudience()) {
          ElMessage.warning('请至少选择一个目标群体或特定用户');
          // 如果验证失败，打开编辑对话框让用户选择受众
          editDialogVisible.value = true;
          return;
        }
        
        // 显示发布中的加载
        const publishLoading = ElLoading.service({
          target: 'body',
          text: '正在发布通知...',
          background: 'rgba(255, 255, 255, 0.7)'
        });
        
        // 处理日期时区问题
        const validFromDate = editForm.value.valid_from;
        const validUntilDate = editForm.value.valid_until;
        
        console.log('直接发布前原始日期数据:', {
          valid_from: validFromDate,
          valid_until: validUntilDate,
          types: {
            valid_from_type: typeof validFromDate,
            valid_until_type: typeof validUntilDate
          }
        });
        
        // 确保日期格式正确并包含时区信息
        if (validFromDate && typeof validFromDate === 'string') {
          try {
            const date = new Date(validFromDate);
            if (!isNaN(date.getTime())) {
              validFromDate = date.toISOString();
              console.log('处理后的开始日期:', validFromDate);
            } else {
              console.error('无效的开始日期格式:', validFromDate);
              // 使用当前日期作为备选
              validFromDate = new Date().toISOString();
            }
          } catch (error) {
            console.error('处理开始日期时出错:', error);
            // 使用当前日期作为备选
            validFromDate = new Date().toISOString();
          }
        } else if (validFromDate instanceof Date) {
          // 如果已经是Date对象，直接转换为ISO字符串
          validFromDate = validFromDate.toISOString();
        } else if (!validFromDate) {
          // 如果未提供日期，使用当前日期
          validFromDate = new Date().toISOString();
        }
        
        if (validUntilDate && typeof validUntilDate === 'string') {
          try {
            const date = new Date(validUntilDate);
            if (!isNaN(date.getTime())) {
              validUntilDate = date.toISOString();
              console.log('处理后的结束日期:', validUntilDate);
            } else {
              console.error('无效的结束日期格式:', validUntilDate);
              // 使用当前日期加7天作为备选
              const futureDate = new Date();
              futureDate.setDate(futureDate.getDate() + 7);
              validUntilDate = futureDate.toISOString();
            }
          } catch (error) {
            console.error('处理结束日期时出错:', error);
            // 使用当前日期加7天作为备选
            const futureDate = new Date();
            futureDate.setDate(futureDate.getDate() + 7);
            validUntilDate = futureDate.toISOString();
          }
        } else if (validUntilDate instanceof Date) {
          // 如果已经是Date对象，直接转换为ISO字符串
          validUntilDate = validUntilDate.toISOString();
        } else if (!validUntilDate) {
          // 如果未提供结束日期，使用当前日期加7天
          const futureDate = new Date();
          futureDate.setDate(futureDate.getDate() + 7);
          validUntilDate = futureDate.toISOString();
        }
        
        // 更新通知内容并添加时区信息
        updateNotification(id, {
          valid_from: validFromDate ? validFromDate.toISOString() : null,
          valid_until: validUntilDate ? validUntilDate.toISOString() : null
        }).then(() => {
          // 定义目标受众
          let publishData = {
            target_groups: targetGroups.value,
            specific_users: specificUsers.value
          };
          
          console.log('发布数据:', publishData); // 调试输出
          
          // 发布通知
          publishNotification(id, publishData).then(response => {
            publishLoading.close();
            
            if (response.data && response.data.code === 200) {
              ElMessage.success('通知发布成功');
              
              // 弹窗询问用户是否前往已发布通知列表
              ElMessageBox.confirm(
                '通知已成功发布。是否查看已发布的通知列表？',
                '发布成功',
                {
                  confirmButtonText: '前往通知列表',
                  cancelButtonText: '留在当前页面',
                  type: 'success',
                  center: true
                }
              )
                .then(() => {
                  // 跳转到已发布通知列表
                  router.push({ name: 'NotificationManagement' });
                })
                .catch(() => {
                  // 留在当前页面，刷新列表
                  fetchData();
                });
            } else {
              ElMessage.error(response.data?.message || '发布失败');
            }
          }).catch(error => {
            publishLoading.close();
            console.error('发布通知失败:', error);
            if (error.response) {
              ElMessage.error(`发布通知失败: ${error.response.data?.message || error.response.status}`);
            } else {
              ElMessage.error('发布通知失败: ' + (error.message || '未知错误'));
            }
          });
        }).catch(error => {
          publishLoading.close();
          console.error('更新通知日期失败:', error);
          if (error.response) {
            ElMessage.error(`更新通知日期失败: ${error.response.data?.message || error.response.status}`);
          } else {
            ElMessage.error('更新通知日期失败: ' + (error.message || '未知错误'));
          }
        });
      }).catch(action => {
        if (action === 'cancel') {
          // 用户选择编辑详情，显示编辑对话框
          editDialogVisible.value = true;
        }
      });
    } else {
      loadingInstance.close();
      ElMessage.error(res.data?.message || '获取通知详情失败，无法发布');
    }
  } catch (error) {
    loadingInstance.close();
    console.error('加载通知详情失败:', error);
    if (error.response) {
      ElMessage.error(`加载通知详情失败: ${error.response.data?.message || error.response.status}`);
    } else {
      ElMessage.error('加载通知详情失败: ' + (error.message || '未知错误'));
    }
  }
};

// 保存新建的草稿
const saveCreate = async () => {
  if (!createFormRef.value) return;
  
  createFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
    try {
      const validFromDate = createForm.value.valid_from;
      const validUntilDate = createForm.value.valid_until;
      
      // 确保日期格式正确
      let formattedValidFrom = null;
      let formattedValidUntil = null;
      
      if (validFromDate) {
        // 确保是Date对象
        const fromDate = validFromDate instanceof Date ? validFromDate : new Date(validFromDate);
        if (!isNaN(fromDate.getTime())) {
          // 有效日期，格式化为ISO字符串
          formattedValidFrom = fromDate.toISOString();
        } else {
          // 无效日期，使用当前时间
          formattedValidFrom = new Date().toISOString();
        }
      } else {
        // 如果没有提供日期，使用当前时间
        formattedValidFrom = new Date().toISOString();
      }
      
      if (validUntilDate) {
        // 确保是Date对象
        const untilDate = validUntilDate instanceof Date ? validUntilDate : new Date(validUntilDate);
        if (!isNaN(untilDate.getTime())) {
          // 有效日期，格式化为ISO字符串
          formattedValidUntil = untilDate.toISOString();
        } else {
          // 无效日期，使用当前时间加7天
          const futureDate = new Date();
          futureDate.setDate(futureDate.getDate() + 7);
          formattedValidUntil = futureDate.toISOString();
        }
      } else {
        // 如果没有提供日期，使用当前时间加7天
        const futureDate = new Date();
        futureDate.setDate(futureDate.getDate() + 7);
        formattedValidUntil = futureDate.toISOString();
      }
      
      const formData = {
        title: createForm.value.title,
        content: createForm.value.content,
        message_type: createForm.value.message_type,
        valid_from: formattedValidFrom,
        valid_until: formattedValidUntil,
        is_draft: true, // 明确指定这是一个草稿
        target_groups: [], // 添加空的目标群体
        specific_users: [] // 添加空的特定用户
      };
      
      console.log('保存草稿数据:', formData);
      
      const response = await createNotification(formData);
      console.log('创建响应:', response);
      
      if (response.data && (response.data.code === 201 || response.data.code === 200)) {
        ElMessage.success('草稿创建成功');
        createDialogVisible.value = false;
        fetchData(); // 刷新列表
      } else {
        ElMessage.error(response.data?.message || '创建失败');
      }
    } catch (error) {
      console.error('创建草稿失败:', error);
      if (error.response) {
        console.error('错误响应:', error.response.data);
        ElMessage.error(`创建草稿失败: ${error.response.data?.message || error.response.status}`);
      } else {
        ElMessage.error('创建草稿失败: ' + (error.message || '未知错误'));
      }
    }
  });
};

// 获取通知类型对应的样式类
const getTypeClass = (type) => {
  const typeMap = {
    '园区公告': 'type-announcement',
    '新闻资讯': 'type-news',
    '审批提醒': 'type-approval',
    '业务提醒': 'type-business',
    '合同提醒': 'type-contract',
    '缴费提醒': 'type-payment',
    '活动推广': 'type-activity',
    '系统通知': 'type-system'
  };
  return typeMap[type] || 'type-default';
};

// 切换搜索栏显示状态
const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
};

// 重置搜索
const resetSearch = () => {
  selectedType.value = '';
  searchQuery.value = '';
  handleSearch();
};
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: normal;
  height: auto;
  min-height: auto;
  display: flex;
  flex-direction: column;
}

.search-form-row {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  margin-bottom: 8px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

/* 卡片列表样式 */
.draft-cards {
  margin-top: 20px;
}

.card-col {
  margin-bottom: 16px;
}

.draft-card {
  height: 240px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  border: 1px solid #ebeef5;
}

.draft-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 0;
}

.card-type {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  background-color: #ecf5ff;
  color: #409eff;
}

/* 不同类型的通知标签颜色 */
.type-announcement {
  background-color: #ecf5ff;
  color: #409eff;
}

.type-news {
  background-color: #f0f9eb;
  color: #67c23a;
}

.type-approval {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.type-business {
  background-color: #f5f7fa;
  color: #909399;
}

.type-contract {
  background-color: #f0f9eb;
  color: #67c23a;
}

.type-payment {
  background-color: #fef0f0;
  color: #f56c6c;
}

.type-activity {
  background-color: #ecf5ff;
  color: #409eff;
}

.type-system {
  background-color: #f5f7fa;
  color: #909399;
}

.type-default {
  background-color: #f5f7fa;
  color: #909399;
}

.card-body {
  flex: 1;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  padding: 0 0 10px 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 1.5;
  height: 48px;
}

.card-preview {
  color: #606266;
  font-size: 14px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  flex: 1;
  line-height: 1.5;
}

.card-footer {
  margin-top: 10px;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 12px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #606266;
  display: flex;
  align-items: center;
  font-size: 18px;
  width: 24px;
  height: 24px;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.el-dropdown-link:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.no-data {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

/* 分页区域 */
.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

/* 添加按钮样式 */
.add-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

/* 保留原有的编辑表单和对话框样式 */
.edit-form-wrapper, .create-form-wrapper {
  padding: 0 20px;
}

.notification-form {
  margin-top: 20px;
}

.info-item :deep(.el-form-item__label) {
  align-self: flex-start;
}

.info-content {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.info-row {
  margin-bottom: 8px;
  display: flex;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  font-weight: bold;
  margin-right: 10px;
  width: 80px;
  display: inline-block;
}

.info-value {
  color: #606266;
}

.compact-audience-selection {
  display: flex;
  align-items: center;
  gap: 15px;
}

.target-groups {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.specific-users {
  flex: 1;
}

.user-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.user-option span {
  font-weight: 500;
}

.user-option small {
  color: #909399;
  font-size: 12px;
  margin-left: 5px;
}

/* 按钮样式优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}

/* Danger Button */
:deep(.el-button--danger) {
  background-color: rgba(245, 108, 108, 0.1) !important;
  color: #F56C6C !important;
  border-color: rgba(245, 108, 108, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--danger:hover) {
  background-color: rgba(245, 108, 108, 0.15) !important;
  border-color: rgba(245, 108, 108, 0.3) !important;
}

/* Success Button */
:deep(.el-button--success) {
  background-color: rgba(103, 194, 58, 0.1) !important;
  color: #67c23a !important;
  border-color: rgba(103, 194, 58, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--success:hover) {
  background-color: rgba(103, 194, 58, 0.15) !important;
  border-color: rgba(103, 194, 58, 0.3) !important;
}

/* 响应式适配 */
@media screen and (max-width: 768px) {
  .header-right {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-toggle-area {
    width: 100%;
    margin-bottom: 10px;
    justify-content: flex-start;
  }

  .search-form {
    max-width: 100%;
    margin-left: 0;
    padding: 0 10px;
    box-sizing: border-box;
    height: auto;
    min-height: 0;
  }
  
  .search-form-row {
    flex-wrap: wrap;
  }
  
  .search-form.is-hidden {
    height: 0;
    min-height: 0;
    padding: 0;
  }

  :deep(.search-form .el-form-item) {
    margin-right: 0;
    width: 100%;
    margin-bottom: 10px;
  }
}
</style> 